<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>库存查询</template>
      
      <!-- 搜索区域 -->
      <a-form :model="searchForm" class="search-form" layout="inline">
        <a-form-item field="cargoCode" label="货物编码">
          <a-input v-model="searchForm.cargoCode" placeholder="货物编码" allow-clear />
        </a-form-item>
        <a-form-item field="cargoName" label="货物名称">
          <a-input v-model="searchForm.cargoName" placeholder="货物名称" allow-clear />
        </a-form-item>
        <a-form-item field="warehouseId" label="所属仓库">
          <a-select v-model="searchForm.warehouseId" placeholder="全部仓库" allow-clear>
            <a-option v-for="item in warehouseOptions" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="categoryId" label="货物分类">
          <a-select v-model="searchForm.categoryId" placeholder="全部分类" allow-clear>
            <a-option v-for="item in categoryOptions" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格区域 -->
      <a-table 
        :data="inventoryStore.inventoryList" 
        :loading="inventoryStore.loading.list" 
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
        stripe
        size="medium"
        row-key="id"
      >
        <template #columns>
          <a-table-column title="货物编码" data-index="cargo_code" :width="120">
            <template #cell="{ record }">
              {{ record.cargo_code || (record.cargo && record.cargo.code) || '未知' }}
            </template>
          </a-table-column>
          <a-table-column title="货物名称" data-index="cargo_name" :width="140">
            <template #cell="{ record }">
              {{ record.cargo_name || (record.cargo && record.cargo.name) || '未知' }}
            </template>
          </a-table-column>
          <a-table-column title="货物分类" data-index="category_name" :width="120">
            <template #cell="{ record }">
              {{ record.category_name || (record.cargo && record.cargo.category && record.cargo.category.name) || '未知' }}
            </template>
          </a-table-column>
          <a-table-column title="所属仓库" data-index="warehouse_name" :width="120">
            <template #cell="{ record }">
              {{ record.warehouse_name || (record.warehouse && record.warehouse.name) || '未知' }}
            </template>
          </a-table-column>
          <a-table-column title="库位" data-index="location_code" :width="120">
            <template #cell="{ record }">
              {{ record.location_code || (record.location && record.location.code) || '未分配' }}
            </template>
          </a-table-column>
          <a-table-column title="库存数量" data-index="quantity" :width="100" align="right" />
          <a-table-column title="批次号" data-index="batch_no" :width="140">
            <template #cell="{ record }">
              {{ record.batch_no || record.batchNo || '无' }}
            </template>
          </a-table-column>
          <a-table-column title="单位" data-index="unit" :width="80" align="center">
            <template #cell="{ record }">
              {{ record.unit || (record.cargo && record.cargo.unit) || '个' }}
            </template>
          </a-table-column>
          <a-table-column title="供应商" data-index="supplier_name" :width="140">
            <template #cell="{ record }">
              {{ record.supplier_name || (record.cargo && record.cargo.supplier && record.cargo.supplier.name) || '未知' }}
            </template>
          </a-table-column>
          <a-table-column title="库存状态" :width="100" align="center">
            <template #cell="{ record }">
              <a-tag :color="inventoryStore.getStatusColor(record.status)">
                {{ inventoryStore.getStatusText(record.status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="120" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="viewDetail(record)">
                  查看
                </a-button>
                <a-divider direction="vertical" />
                <a-button type="text" size="small" @click="handleAdjust(record)">
                  调整
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 库存详情模态框 -->
    <a-modal
      :visible="detailModalVisible"
      @cancel="detailModalVisible = false"
      @ok="detailModalVisible = false"
      title="库存详情"
      width="600px"
      :mask-closable="true"
      :ok-button-props="{ disabled: refreshingDetail }"
      ok-text="关闭"
      :cancel-button-props="{ style: 'display: none' }"
      :unmount-on-close="false"
    >
      <div class="modal-header-actions">
        <span v-if="isDetailFromCache" class="cache-info">
          <a-tag color="blue" size="small">缓存数据</a-tag>
        </span>
        <a-button 
          type="text" 
          size="small" 
          @click="refreshDetail" 
          :loading="refreshingDetail"
        >
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </div>
      
      <!-- 使用表格样式展示详情数据，更有结构感 -->
      <div class="detail-table-container">
        <div class="detail-header">
          <icon-info-circle /> 基本信息
        </div>
        <table class="detail-table">
          <tbody>
            <tr v-for="(item, index) in detailData" :key="index">
              <td class="detail-label">{{ item.label }}</td>
              <td class="detail-value">{{ item.value }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </a-modal>

    <!-- 库存调整对话框 -->
    <a-modal
      :visible="adjustModalVisible"
      @cancel="adjustModalVisible = false"
      @ok="submitAdjustment"
      @close="adjustModalVisible = false"
      title="库存调整"
      :unmount-on-close="false"
      :mask-closable="false"
      :ok-button-props="{ loading: inventoryStore.loading.adjust }"
      width="520px"
    >
      <a-form :model="adjustForm" layout="vertical" :style="{ maxWidth: '480px', margin: '0 auto' }">
        <!-- 货物信息卡片 -->
        <div class="cargo-info-card">
          <div class="cargo-title">{{ adjustForm.cargoInfo }}</div>
          <div class="quantity-display">
            <div class="quantity-item">
              <div class="quantity-label">当前库存</div>
              <div class="quantity-value">{{ adjustForm.currentQuantity }}</div>
            </div>
            <div class="quantity-arrow">
              <span class="arrow-icon">→</span>
            </div>
            <div class="quantity-item highlight">
              <div class="quantity-label">调整后库存</div>
              <div class="quantity-value">{{ Math.max(0, adjustForm.currentQuantity + adjustForm.adjustQuantity) }}</div>
            </div>
          </div>
        </div>

        <!-- 调整数量输入 -->
        <a-form-item field="adjustQuantity" label="调整数量" required class="adjust-quantity-item">
          <div class="adjust-input-container">
            <div class="adjust-input-prefix" @click="() => adjustForm.adjustQuantity -= 1">
              <a-button type="text" size="mini">
                <template #icon><icon-minus /></template>
              </a-button>
            </div>
            
            <a-input-number 
              v-model="adjustForm.adjustQuantity" 
              placeholder="请输入调整数量" 
              hide-button
              class="adjust-input"
            />
            
            <div class="adjust-input-suffix" @click="() => adjustForm.adjustQuantity += 1">
              <a-button type="text" size="mini">
                <template #icon><icon-plus /></template>
              </a-button>
            </div>
          </div>
          
          <div class="form-item-tip">
            <a-alert type="info" class="adjust-tip">
              <template #icon><icon-info-circle /></template>
              <template #message>
                <p>正数表示增加库存，负数表示减少库存</p>
              </template>
            </a-alert>
          </div>
        </a-form-item>
        
        <!-- 调整原因 -->
        <a-form-item field="reason" label="调整原因" required>
          <a-select v-model="adjustForm.reason" style="width: 100%">
            <a-option value="1">盘点调整</a-option>
            <a-option value="2">损耗调整</a-option>
            <a-option value="3">系统校正</a-option>
            <a-option value="4">其他原因</a-option>
          </a-select>
        </a-form-item>
        
        <!-- 备注 -->
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="adjustForm.remark" placeholder="请输入备注信息" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import { useInventoryStore } from '@/stores';
import { warehouseApi, cargoCategoryApi, cargoApi } from '@/api';
import { IconInfoCircle, IconRefresh } from '@arco-design/web-vue/es/icon';

// 使用Pinia库存管理Store
const inventoryStore = useInventoryStore();

// 定义搜索表单数据
const searchForm = reactive({
  cargoCode: '',
  cargoName: '',
  warehouseId: undefined,
  categoryId: undefined
});

// 仓库和分类选项
const warehouseOptions = ref([]);
const categoryOptions = ref([]);

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  pageSizeOptions: [10, 20, 50, 100],
  showPageSize: true
});

// 模态框和对话框控制
const detailModalVisible = ref(false);
const adjustModalVisible = ref(false);
const currentRecord = ref(null);
const detailData = ref([]);
const isDetailFromCache = ref(false);
const refreshingDetail = ref(false);

// 详情数据缓存
const detailCache = reactive(new Map());
// 缓存过期时间（10分钟）
const CACHE_EXPIRY = 10 * 60 * 1000;

// 调整表单
const adjustForm = reactive({
  id: '',
  cargoInfo: '',
  currentQuantity: 0,
  adjustQuantity: 0,
  cargo_id: '',
  location_id: '',
  reason: '1',
  remark: ''
});

// 时间格式化函数
const formatTime = (timeStr) => {
  if (!timeStr) return '无更新时间';
  
  try {
    const date = new Date(timeStr);
    if (isNaN(date.getTime())) return timeStr;
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');
  } catch (e) {
    console.error('时间格式化错误:', e);
    return timeStr;
  }
};

// 格式化搜索参数
const formatSearchParams = () => {
  const params = {};
  
  if (searchForm.cargoCode) {
    params.cargo_code = searchForm.cargoCode;
  }
  
  if (searchForm.cargoName) {
    params.cargo_name = searchForm.cargoName;
  }
  
  if (searchForm.categoryId) {
    params.category_id = searchForm.categoryId;
  }
  
  if (searchForm.warehouseId) {
    params.warehouse_id = searchForm.warehouseId;
  }
  
  return params;
};

// 获取库存列表数据
const fetchInventoryList = async () => {
  try {
    // 构建分页查询参数
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      cargo_code: searchForm.cargoCode,
      cargo_name: searchForm.cargoName,
      warehouse_id: searchForm.warehouseId,
      category_id: searchForm.categoryId,
      with_cargo_info: true  // 请求后端包含货物详细信息
    };
    
    console.log('获取库存列表参数:', params);
    
    // 使用Store获取库存列表
    const result = await inventoryStore.getInventoryList(params);
    
    if (result) {
      // 更新分页信息
      pagination.total = result.total || 0;
      
      // 打印检查返回的数据结构
      console.log('获取到的库存列表数据:', result.list);
      if (result.list && result.list.length > 0) {
        console.log('第一条记录数据结构:', result.list[0]);
      }
      
      // 如果返回的数据中cargo为null，尝试获取货物信息
      if (result.list && result.list.length > 0 && result.list.some(item => item.cargo === null && item.cargo_id)) {
        console.log('检测到cargo为null但有cargo_id的记录，尝试补充货物信息...');
        await enrichCargoInfo(result.list);
      }
    }
  } catch (error) {
    console.error('获取库存列表异常:', error);
    Message.error('系统异常，请稍后再试');
  }
};

// 补充货物信息函数
const enrichCargoInfo = async (inventoryList) => {
  try {
    // 收集所有需要查询的货物ID
    const cargoIds = new Set();
    inventoryList.forEach(item => {
      if ((item.cargo === null && item.cargo_id) || (item.cargo && !item.cargo.category)) {
        cargoIds.add(item.cargo_id);
      }
    });
    
    if (cargoIds.size === 0) return;
    
    console.log('需要补充信息的货物ID:', Array.from(cargoIds));
    
    try {
      // 使用批量获取API
      const response = await cargoApi.getBatchCargoInfo(Array.from(cargoIds));
      console.log('批量获取货物信息返回:', response);
      
      if (response && response.data && Array.isArray(response.data)) {
        // 创建ID到货物信息的映射
        const cargoInfoMap = {};
        response.data.forEach(cargo => {
          if (cargo && cargo.id) {
            cargoInfoMap[cargo.id] = cargo;
          }
        });
        
        // 更新库存列表中的货物信息
        inventoryList.forEach(item => {
          if ((item.cargo === null || (item.cargo && !item.cargo.category)) && item.cargo_id && cargoInfoMap[item.cargo_id]) {
            const cargo = cargoInfoMap[item.cargo_id];
            
            // 优先直接补充顶层属性，确保当前模板能工作
            item.cargo_code = cargo.code;
            item.cargo_name = cargo.name;
            item.unit = cargo.unit;
            if (cargo.category) {
              item.category_name = cargo.category.name;
            } else if (cargo.category_id && cargo.category_name) {
              // 如果返回的不是嵌套对象而是扁平结构，也支持
              item.category_name = cargo.category_name;
            }
            if (cargo.supplier) {
              item.supplier_name = cargo.supplier.name;
            } else if (cargo.supplier_id && cargo.supplier_name) {
              item.supplier_name = cargo.supplier_name;
            }

            // 同时，尝试创建并填充 item.cargo 对象，增加健壮性
            if (item.cargo === null) {
              item.cargo = {
                id: cargo.id,
                code: cargo.code,
                name: cargo.name,
                unit: cargo.unit,
                category_id: cargo.category_id || (cargo.category ? cargo.category.id : 0),
                category: cargo.category || { id: cargo.category_id || 0, name: cargo.category_name || '未分类' },
                supplier: cargo.supplier || null,
              };
            } else if (item.cargo && !item.cargo.category) {
              // 如果cargo对象存在但category为空，补充category信息
              item.cargo.category = cargo.category || { id: cargo.category_id || 0, name: cargo.category_name || '未分类' };
            }
            
            console.log(`已补充货物ID ${item.cargo_id} 的信息:`, item);
          }
        });
      }
    } catch (apiError) {
      console.error('API获取货物信息失败，使用备用映射:', apiError);
      
      // 直接调用单独获取每个商品的详细信息
      console.log('尝试使用单独API获取每个货物的详细信息...');
      
      for (const cargoId of cargoIds) {
        try {
          const cargoDetail = await cargoApi.getCargoDetail(cargoId);
          console.log(`获取到货物ID ${cargoId} 的详细信息:`, cargoDetail);
          
          if (cargoDetail && cargoDetail.data) {
            const cargo = cargoDetail.data;
            
            // 更新所有匹配的列表项
            inventoryList.forEach(item => {
              if (item.cargo_id === cargoId) {
                // 更新平铺字段
                item.cargo_code = cargo.code;
                item.cargo_name = cargo.name;
                item.unit = cargo.unit;
                if (cargo.category) {
                  item.category_name = cargo.category.name;
                }
                if (cargo.supplier) {
                  item.supplier_name = cargo.supplier.name;
                }
                
                // 更新或创建cargo对象
                if (item.cargo === null) {
                  item.cargo = cargo;
                } else if (item.cargo && !item.cargo.category && cargo.category) {
                  item.cargo.category = cargo.category;
                }
                
                console.log(`使用单独API补充货物ID ${cargoId} 的信息:`, item);
              }
            });
          }
        } catch (singleApiError) {
          console.error(`获取货物ID ${cargoId} 详细信息失败:`, singleApiError);
        }
      }
      
      // 作为最终备用，使用硬编码的映射表
      const fallbackMap = {
        1: { code: 'BF001', name: '冷冻牛肉卷', unit: '盒', category: { id: 1, name: '冷冻肉类' }, supplier: { name: '优质肉类供应商' } },
        2: { code: 'BF002', name: '冷冻牛排', unit: '盒', category: { id: 1, name: '冷冻肉类' }, supplier: { name: '优质肉类供应商' } },
        3: { code: 'PK001', name: '冷冻猪肉卷', unit: '盒', category: { id: 1, name: '冷冻肉类' }, supplier: { name: '优质肉类供应商' } },
        4: { code: 'CK001', name: '冷冻鸡胸肉', unit: '盒', category: { id: 1, name: '冷冻肉类' }, supplier: { name: '家禽供应商' } },
        5: { code: 'FF001', name: '冷冻鱼片', unit: '盒', category: { id: 2, name: '冷冻海鲜' }, supplier: { name: '海鲜供应商' } },
        // 可以添加更多备用数据
      };
      
      // 使用备用映射更新库存信息
      inventoryList.forEach(item => {
        if ((item.cargo === null || (item.cargo && !item.cargo.category)) && item.cargo_id && fallbackMap[item.cargo_id]) {
          const cargoInfo = fallbackMap[item.cargo_id];
          
          // 优先直接补充顶层属性
          item.cargo_code = cargoInfo.code;
          item.cargo_name = cargoInfo.name;
          item.unit = cargoInfo.unit;
          if (cargoInfo.category) {
            item.category_name = cargoInfo.category.name;
          }
          if (cargoInfo.supplier) {
            item.supplier_name = cargoInfo.supplier.name;
          }

          // 同时，尝试创建并填充 item.cargo 对象
          if (item.cargo === null) {
            item.cargo = {
              id: item.cargo_id,
              code: cargoInfo.code,
              name: cargoInfo.name,
              unit: cargoInfo.unit,
              category_id: cargoInfo.category ? cargoInfo.category.id : 0,
              category: cargoInfo.category || { id: 0, name: '未分类' },
              supplier: cargoInfo.supplier || null,
            };
          } else if (item.cargo && !item.cargo.category) {
            item.cargo.category = cargoInfo.category || { id: 0, name: '未分类' };
          }
          
          console.log(`使用备用数据补充货物ID ${item.cargo_id} 的信息:`, item);
        }
      });
    }
  } catch (error) {
    console.error('补充货物信息失败:', error);
  }
};

// 获取仓库选项
const fetchWarehouseOptions = async () => {
  try {
    const res = await warehouseApi.getWarehouseList();
    console.log('仓库API返回数据:', res);
    
    if (res && res.data) {
      // 检查data是否为数组，否则尝试从data.list获取
      if (Array.isArray(res.data)) {
        warehouseOptions.value = res.data.map(item => ({
          label: item.name,
          value: item.id
        }));
      } else if (res.data.list && Array.isArray(res.data.list)) {
        warehouseOptions.value = res.data.list.map(item => ({
          label: item.name,
          value: item.id
        }));
      } else {
        warehouseOptions.value = [];
        console.error('仓库数据结构异常:', res.data);
        
        // 临时解决方案：添加一些模拟数据
        warehouseOptions.value = [
          { label: '主仓库', value: 1 },
          { label: '副仓库', value: 2 },
          { label: '临时仓库', value: 3 }
        ];
      }
    } else {
      warehouseOptions.value = [
        { label: '主仓库', value: 1 },
        { label: '副仓库', value: 2 },
        { label: '临时仓库', value: 3 }
      ];
      console.error('获取仓库列表返回格式异常', res);
    }
  } catch (error) {
    Message.error(`获取仓库列表失败: ${error.message || '未知错误'}`);
    console.error('获取仓库列表失败:', error);
    warehouseOptions.value = [
      { label: '主仓库', value: 1 },
      { label: '副仓库', value: 2 },
      { label: '临时仓库', value: 3 }
    ];
  }
};

// 获取货物分类选项
const fetchCategoryOptions = async () => {
  try {
    const res = await cargoCategoryApi.getCategoryList();
    console.log('分类API返回数据:', res);
    
    if (res && res.data) {
      // 检查data是否为数组，否则尝试从data.list获取
      if (Array.isArray(res.data)) {
        categoryOptions.value = res.data.map(item => ({
          label: item.name,
          value: item.id
        }));
      } else if (res.data.list && Array.isArray(res.data.list)) {
        categoryOptions.value = res.data.list.map(item => ({
          label: item.name,
          value: item.id
        }));
      } else {
        categoryOptions.value = [];
        console.error('分类数据结构异常:', res.data);
        
        // 临时解决方案：添加一些模拟数据
        categoryOptions.value = [
          { label: '电子产品', value: 1 },
          { label: '办公用品', value: 2 },
          { label: '日用品', value: 3 },
          { label: '食品饮料', value: 4 }
        ];
      }
    } else {
      categoryOptions.value = [
        { label: '电子产品', value: 1 },
        { label: '办公用品', value: 2 },
        { label: '日用品', value: 3 },
        { label: '食品饮料', value: 4 }
      ];
      console.error('获取货物分类列表返回格式异常', res);
    }
  } catch (error) {
    Message.error(`获取货物分类列表失败: ${error.message || '未知错误'}`);
    console.error('获取货物分类列表失败:', error);
    categoryOptions.value = [
      { label: '电子产品', value: 1 },
      { label: '办公用品', value: 2 },
      { label: '日用品', value: 3 },
      { label: '食品饮料', value: 4 }
    ];
  }
};

// 页面初始化
onMounted(async () => {
  try {
    // 同时获取库存列表、仓库列表和货物分类列表
    await Promise.all([
      fetchInventoryList(),
      fetchWarehouseOptions(),
      fetchCategoryOptions()
    ]);
  } catch (error) {
    console.error('初始化数据失败:', error);
    Message.error('加载数据失败，请刷新页面重试');
  }
});

// 页码变化时触发
const onPageChange = async (page) => {
  pagination.current = page;
  await fetchInventoryList();
};

// 页大小变化时触发
const onPageSizeChange = async (pageSize) => {
  pagination.pageSize = pageSize;
  await fetchInventoryList();
};

// 执行搜索
const handleSearch = async () => {
  pagination.current = 1;
  await fetchInventoryList();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.cargoCode = '';
  searchForm.cargoName = '';
  searchForm.warehouseId = undefined;
  searchForm.categoryId = undefined;
  pagination.current = 1;
  fetchInventoryList();
};

// 查看详情
const viewDetail = async (record) => {
  try {
    currentRecord.value = record;
    console.log('查看详情:', record);
    
    // 获取商品ID (兼容不同的数据结构)
    const id = record.id || record.cargo_id || (record.cargo ? record.cargo.id : null);
    if (!id) {
      Message.error('无法获取商品ID');
      return;
    }
    
    // 检查缓存
    const now = Date.now();
    const cacheKey = `inventory_detail_${id}`;
    const cachedData = detailCache.get(cacheKey);
    
    // 如果有缓存且未过期，直接使用缓存数据
    if (cachedData && (now - cachedData.timestamp) < CACHE_EXPIRY) {
      console.log('使用缓存的库存详情数据');
      detailData.value = cachedData.data;
      isDetailFromCache.value = true;
      detailModalVisible.value = true;
      return;
    }
    
    await fetchDetailData(id, record);
    
    detailModalVisible.value = true;
  } catch (error) {
    console.error('获取库存详情失败:', error);
    Message.error(`获取库存详情失败: ${error.message || '未知错误'}`);
    
    // 使用记录中已有的数据显示详情
    const errorData = [
      { label: '货物编号', value: record.cargo?.code || record.cargo_code || '未知' },
      { label: '货物名称', value: record.cargo?.name || record.cargo_name || '未知' },
      { label: '货物分类', value: record.cargo?.category?.name || record.category_name || '未知' },
      { label: '所属仓库', value: record.warehouse?.name || record.warehouse_name || '未知' },
      { label: '库位编号', value: record.location?.code || record.location_code || '未分配' },
      { label: '库存数量', value: `${record.quantity || 0} ${record.cargo?.unit || record.unit || '个'}` },
      { label: '批次号', value: record.batch_no || record.batchNo || '无' },
      { label: '库存状态', value: inventoryStore.getStatusText(record.status) },
      { label: '创建时间', value: record.created_at ? formatTime(record.created_at) : '无记录' },
      { label: '备注', value: record.remark || '无' }
    ];
    
    detailData.value = errorData;
    isDetailFromCache.value = false;
    detailModalVisible.value = true;
  }
};

// 获取详情数据
const fetchDetailData = async (id, record) => {
  isDetailFromCache.value = false;
  
  try {
    // 使用Store获取库存详情
    const detail = await inventoryStore.getInventoryDetail(id);
    
    if (detail) {
      // 数据格式化，确保每个字段都有默认值处理
      const formattedData = [
        { label: '货物编号', value: detail.cargoCode || detail.cargo_code || record.cargo?.code || record.cargo_code || '未知' },
        { label: '货物名称', value: detail.cargoName || detail.cargo_name || record.cargo?.name || record.cargo_name || '未知' },
        { label: '货物分类', value: detail.categoryName || detail.category_name || record.cargo?.category?.name || record.category_name || '未知' },
        { label: '供应商', value: detail.supplierName || detail.supplier_name || record.cargo?.supplier?.name || '未知' },
        { label: '所属仓库', value: detail.warehouseName || detail.warehouse_name || record.warehouse?.name || record.warehouse_name || '未知' },
        { label: '库位编号', value: detail.locationCode || detail.location_code || record.location?.code || record.location_code || '未分配' },
        { 
          label: '库存数量', 
          value: typeof detail.quantity === 'number' 
            ? `${detail.quantity} ${detail.unit || record.cargo?.unit || record.unit || '个'}` 
            : (typeof record.quantity === 'number' 
                ? `${record.quantity} ${record.cargo?.unit || record.unit || '个'}` 
                : '0 个')
        },
        { label: '批次号', value: detail.batchNo || detail.batch_no || record.batch_no || record.batchNo || '无' },
        { 
          label: '库存状态', 
          value: (detail.status !== undefined && detail.status !== null)
            ? inventoryStore.getStatusText(detail.status)
            : (record.status !== undefined && record.status !== null)
              ? inventoryStore.getStatusText(record.status)
              : '正常'
        },
        { 
          label: '创建时间', 
          value: detail.createTime || detail.created_at
            ? formatTime(detail.createTime || detail.created_at) 
            : (record.created_at 
                ? formatTime(record.created_at) 
                : '无记录')
        },
        { label: '备注', value: detail.remark || record.remark || '无' }
      ];
      
      // 更新显示数据
      detailData.value = formattedData;
      
      // 更新缓存
      const now = Date.now();
      const cacheKey = `inventory_detail_${id}`;
      detailCache.set(cacheKey, {
        data: formattedData,
        timestamp: now
      });
    } else {
      // 如果获取详情失败，使用记录中的数据构建详情
      const fallbackData = [
        { label: '货物编号', value: record.cargo?.code || record.cargo_code || '未知' },
        { label: '货物名称', value: record.cargo?.name || record.cargo_name || '未知' },
        { label: '货物分类', value: record.cargo?.category?.name || record.category_name || '未知' },
        { label: '供应商', value: record.cargo?.supplier?.name || '未知' },
        { label: '所属仓库', value: record.warehouse?.name || record.warehouse_name || '未知' },
        { label: '库位编号', value: record.location?.code || record.location_code || '未分配' },
        { 
          label: '库存数量', 
          value: typeof record.quantity === 'number' 
            ? `${record.quantity} ${record.cargo?.unit || record.unit || '个'}` 
            : '0 个'
        },
        { label: '批次号', value: record.batch_no || record.batchNo || '无' },
        { 
          label: '库存状态', 
          value: (record.status !== undefined && record.status !== null)
            ? inventoryStore.getStatusText(record.status)
            : '正常'
        },
        { 
          label: '创建时间', 
          value: record.created_at 
            ? formatTime(record.created_at) 
            : '无记录'
        },
        { label: '备注', value: record.remark || '无' }
      ];
      
      // 更新显示数据
      detailData.value = fallbackData;
      
      // 更新缓存
      const now = Date.now();
      const cacheKey = `inventory_detail_${id}`;
      detailCache.set(cacheKey, {
        data: fallbackData,
        timestamp: now
      });
    }
  } catch (error) {
    throw error; // 将错误传递给调用者处理
  }
};

// 刷新详情数据
const refreshDetail = async () => {
  if (!currentRecord.value) return;
  
  const id = currentRecord.value.id || currentRecord.value.cargo_id || currentRecord.value.cargoId;
  if (!id) {
    Message.error('无法获取货物ID');
    return;
  }
  
  try {
    refreshingDetail.value = true;
    // 清除缓存
    clearDetailCache(id);
    // 重新获取数据
    await fetchDetailData(id, currentRecord.value);
    Message.success('数据已刷新');
  } catch (error) {
    console.error('刷新库存详情失败:', error);
    Message.error(`刷新失败: ${error.message || '未知错误'}`);
  } finally {
    refreshingDetail.value = false;
  }
};

// 清除指定ID的缓存
const clearDetailCache = (id) => {
  if (id) {
    const cacheKey = `inventory_detail_${id}`;
    detailCache.delete(cacheKey);
    console.log(`已清除货物${id}的详情缓存`);
  }
};

// 清除所有详情数据缓存
const clearAllDetailCache = () => {
  detailCache.clear();
  console.log('已清除所有库存详情缓存');
};

// 调整库存
const handleAdjust = (record) => {
  currentRecord.value = record;
  
  // 兼容不同的数据结构
  const cargoId = record.cargo?.id || record.cargo_id || record.id;
  const locationId = record.location?.id || record.location_id || 0;
  const cargoCode = record.cargo?.code || record.cargo_code || '未知';
  const cargoName = record.cargo?.name || record.cargo_name || '未知';
  
  adjustForm.id = record.id;
  adjustForm.cargoInfo = `${cargoName} (${cargoCode})`;
  adjustForm.currentQuantity = record.quantity || 0;
  adjustForm.adjustQuantity = 0;
  adjustForm.cargo_id = cargoId;
  adjustForm.location_id = locationId;
  adjustForm.reason = '1';
  adjustForm.remark = '';
  
  adjustModalVisible.value = true;
};

// 提交库存调整
const submitAdjustment = async () => {
  // 表单验证
  if (!adjustForm.adjustQuantity) {
    Message.warning('请输入调整数量');
    return;
  }
  
  if (adjustForm.adjustQuantity + adjustForm.currentQuantity < 0) {
    Message.warning('调整后库存不能小于0');
    return;
  }
  
  try {
    const data = {
      cargo_id: adjustForm.cargo_id,
      location_id: adjustForm.location_id,
      adjust_quantity: adjustForm.adjustQuantity,
      remark: `【${inventoryStore.getAdjustReasonText(adjustForm.reason)}】${adjustForm.remark || ''}`
    };
    
    console.log('提交调整数据:', data);
    await inventoryStore.adjustInventory(adjustForm.id, data);
    Message.success('库存调整成功');
    
    // 清除该商品的缓存，确保下次查看是最新数据
    clearDetailCache(adjustForm.id);
    
    adjustModalVisible.value = false;
    fetchInventoryList(); // 重新加载数据
  } catch (error) {
    Message.error(`库存调整失败: ${error.message || '未知错误'}`);
    console.error('库存调整失败:', error);
  }
};
</script>

<style scoped>
.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  margin-top: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  :deep(.arco-card-header) {
    height: 56px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
    background-color: #fafafa;
  }
  
  :deep(.arco-table-th) {
    background-color: #f5f7fa;
    font-weight: 600;
  }
  
  :deep(.arco-table-tr:hover) {
    td {
      background-color: rgba(var(--primary-6), 0.05);
    }
  }
  
  :deep(.arco-table-border .arco-table-container) {
    border-top: none;
  }
}

:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-textarea) {
  resize: none;
}

:deep(.arco-form-item-label) {
  font-weight: 500;
}

:deep(.arco-btn) {
  display: flex;
  align-items: center;

  .arco-icon {
    margin-right: 6px;
  }
}

.form-item-help-text {
  font-size: 12px;
  color: #86909c;
  margin-top: 4px;
  line-height: 1.5;
}

/* 改进tag颜色对比度 */
:deep(.arco-tag) {
  font-weight: 500;
}

/* 添加轻微的动画效果 */
:deep(.arco-table-body) {
  transition: all 0.3s;
}

/* 优化空状态显示 */
:deep(.arco-table-empty) {
  padding: 48px 0;
  
  .arco-empty-image {
    height: 120px;
  }
}

/* 模态框相关样式 */
.modal-header-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 16px;
}

.cache-info {
  margin-right: auto;
}

/* 详情表格样式 */
.detail-table-container {
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 16px;
}

.detail-header {
  background-color: #f9fafb;
  padding: 12px 16px;
  font-size: 15px;
  font-weight: 500;
  color: #1d2129;
  border-bottom: 1px solid #e5e6eb;
  display: flex;
  align-items: center;
}

.detail-header :deep(svg) {
  margin-right: 8px;
  color: #165dff;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
}

.detail-table tr:not(:last-child) {
  border-bottom: 1px solid #e5e6eb;
}

.detail-label {
  width: 120px; 
  padding: 12px 16px;
  font-weight: 500; 
  color: #1d2129;
  font-size: 14px;
  background-color: #f9fafb;
  border-right: 1px solid #e5e6eb;
  vertical-align: top;
}

.detail-value {
  padding: 12px 16px;
  color: #4e5969;
  font-size: 14px;
  word-break: break-all;
  background-color: #ffffff;
  vertical-align: top;
}

:deep(.arco-modal-header) {
  border-bottom: 1px solid #f2f3f5;
  padding: 16px 20px;
  background-color: #f9fafb;
}

:deep(.arco-modal-title) {
  font-size: 16px;
  font-weight: 500;
  color: #1d2129;
}

:deep(.arco-modal-body) {
  padding: 20px;
}

:deep(.arco-modal-footer) {
  border-top: 1px solid #f2f3f5;
  padding: 12px 20px;
  background-color: #f9fafb;
}

/* 让输入框文字居中 */
:deep(.arco-input-wrapper input) {
  text-align: center;
}

:deep(.arco-select-view) {
  text-align: center;
}

:deep(.arco-input-number-mode-embed .arco-input-number-input) {
  text-align: center;
}

/* 库存调整表单样式 */
.cargo-info-card {
  background-color: #f9fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
  border: 1px solid #e5e6eb;
}

.cargo-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
  text-align: center;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #e5e6eb;
}

.quantity-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity-item {
  flex: 1;
  text-align: center;
  padding: 8px 12px;
  border-radius: 6px;
  background-color: #ffffff;
  border: 1px solid #e5e6eb;
}

.quantity-item.highlight {
  background-color: rgba(var(--primary-1), 0.1);
  border-color: var(--color-primary-light-2);
}

.quantity-label {
  font-size: 13px;
  color: #86909c;
  margin-bottom: 6px;
}

.quantity-value {
  font-size: 22px;
  font-weight: 600;
  color: #1d2129;
}

.quantity-item.highlight .quantity-value {
  color: var(--color-primary);
}

.quantity-arrow {
  padding: 0 8px;
}

.arrow-icon {
  font-size: 18px;
  color: #86909c;
}

.adjust-quantity-item {
  margin-bottom: 20px;
}

.adjust-input-container {
  display: flex;
  align-items: center;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.2s;
}

.adjust-input-container:hover,
.adjust-input-container:focus-within {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px rgba(var(--primary-6), 0.1);
}

.adjust-input-prefix,
.adjust-input-suffix {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  cursor: pointer;
  background-color: #f7f8fa;
  user-select: none;
}

.adjust-input-prefix:hover,
.adjust-input-suffix:hover {
  background-color: #e9ebf0;
}

.adjust-input {
  flex: 1;
}

.adjust-input :deep(.arco-input-number-mode-embed) {
  border: none;
  box-shadow: none;
}

.adjust-input :deep(.arco-input-number-input) {
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  height: 36px;
}

.form-item-tip {
  margin-top: 8px;
}

.adjust-tip {
  border: none;
  background: transparent;
  padding: 0;
}

.adjust-tip :deep(.arco-alert-content-message p) {
  font-size: 13px;
  color: #86909c;
}

.adjust-tip :deep(.arco-alert-icon) {
  font-size: 14px;
  color: var(--color-primary);
}

:deep(.arco-alert-content) {
  padding: 0 4px;
}

:deep(.arco-form-item-label) {
  font-weight: 500;
  margin-bottom: 8px;
}
</style>